use rocket::http::{Header, Method, Status};
use rocket::request::Request;
use rocket::response::{self, Responder, Response};

pub struct CorsOptions {
    pub allowed_methods: &'static [&'static str],
    pub allowed_headers: &'static [&'static str],
}

impl<'r> Responder<'r, 'static> for &'r CorsOptions {
    fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
        if req.method() != Method::Options {
            panic!("Invalid method: {}", req.method());
        }
        Response::build()
            .status(Status::Ok)
            .header(Header::new(
                "Access-Control-Allow-Methods",
                self.allowed_methods.join(","),
            ))
            .header(Header::new(
                "Access-Control-Allow-Headers",
                [self.allowed_headers, &["Content-Type"]].concat().join(","),
            ))
            .ok()
    }
}
